<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Controller;

use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use User\Entity\UserGoodsFavorites;
use User\Service\UserGoodsFavoritesManager;

class HomeFavoritesController extends HomeActionController
{
    private $translator;
    private $writeEntityManager;
    private $userGoodsFavoritesManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $writeEntityManager,
        UserGoodsFavoritesManager $userGoodsFavoritesManager
    )
    {
        $this->translator           = $translator;
        $this->writeEntityManager   = $writeEntityManager;
        $this->userGoodsFavoritesManager = $userGoodsFavoritesManager;
    }

    /**
     * 商品收藏列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('我的商品收藏'));

        $page       = (int) $this->params()->fromQuery('page', 1);
        $query      = $this->writeEntityManager->getRepository(UserGoodsFavorites::class)->shopGoodsFavoritesList(parent::$userId);
        $paginator  = $this->shopPlugin()->shopPaginator($query, $page, $this->shopPlugin()->shopPerPageNum('favoritesList'));

        return ['goodsFavoritesList' => $paginator];
    }

    /**
     * 收藏商品删除
     * @return JsonModel
     */
    public function deleteGoodsFavoritesAction()
    {
        $goodsFavoritesId   = $this->params()->fromRoute('id', -1);
        $goodsFavoritesInfo = $this->writeEntityManager->getRepository(UserGoodsFavorites::class)->findOneBy(['userId' => parent::$userId, 'goodsFavoritesId' => $goodsFavoritesId]);
        if($goodsFavoritesInfo == null) return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('该收藏商品不存在!')]);

        if($this->userGoodsFavoritesManager->deleteUserGoodsFavorites($goodsFavoritesId, parent::$userId)) return new JsonModel(['status' => 'true']);

        return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('收藏商品删除失败!')]);
    }
}